<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //-1 2 1 -4   target=1
      //-4 -1 1 2
      var threeSum = function (nums, target) {
        nums.sort((a, b) => a - b)
        let res = Infinity
        let result = 0
        //双指针计算三数之和
        for (let i = 0; i < nums.length; i++) {
          //-1 -1 -1 1 2
          if (nums[i] == nums[i - 1]) continue
          let left = i + 1
          let right = nums.length - 1
          while (left < right) {
            let sum = nums[i] + nums[left] + nums[right]
            if (sum == target) return sum
            if (Math.abs(res) > Math.abs(sum - target)) {
              res = sum - target
              result = sum
            }
            if (sum < target) {
              left++
            } else {
              right--
            }
          }
        }
        console.log(result)
      }
      threeSum([-4, -1, 1, 2], 1)
    </script>
  </body>
</html>
